use gloo_net::http::Request;
use serde::Deserialize;
use serde_json::json;

use super::APP_HOST;

#[derive(PartialEq)]
pub struct User {
  pub id: i32,
  pub username: String,
  pub created_at: String,
}

#[derive(Deserialize)]
pub struct LoginResponse {
  pub token: String,
}

#[derive(Deserialize)]
pub struct MeResponse {
  pub id: i32,
  pub username: String,
  pub created_at: String,
}

pub async fn api_login(
  username: String,
  password: String,
) -> Result<LoginResponse, gloo_net::Error> {
  let request_url = format!("{}/login", APP_HOST);

  let resp = Request::post(&request_url)
    .json(&json!({
      "username": username,
      "password": password
    }))?
    .send()
    .await?;

  resp.json::<LoginResponse>().await
}

pub async fn api_me(token: &str) -> Result<MeResponse, gloo_net::Error> {
  let request_url = format!("{}/me", APP_HOST);

  let resp = Request::get(&request_url)
    .header("Authorization", &format!("Bearer {}", token))
    .send()
    .await?;

  resp.json::<MeResponse>().await
}
